/**
 * Created by Administrator on 2015/12/5.
 */
var mongodb = require('mongodb');
var ObjectID = mongodb.ObjectID;
var MongoClient = mongodb.MongoClient;
var assert = require('assert');
var Q = require('q');
var url = 'mongodb://localhost:27017/mydb';
var conn = require('./conn');


/**
 * 具备分页功能
 * @param page
 * @param callback
 * callback({
 *  total:count,
 *  articles:[]
 * })
 */

/**
 * {
 *  _id:
 *  title:
 *  body:
 *  date:
 *  user:{_id:,name:}
 *  keywords:[]
 *  }
 */
function getArticle(_id,callback){
    var p = conn.getConnection();
    var connection = undefined;
    p.then(function(db){
        var blog = db.collection('blog');
        connection = db;
        return blog.findOne({_id:ObjectID.createFromHexString(_id)});
    }).then(function(doc){
        doc._id = doc._id.toHexString();
        callback(doc);
    }).finally(function(){
        connection.close();
    })
}

function newArticle(article,callback){
    var p = conn.getConnection();
    var connection = undefined;
    p.then(function(db){
        var article = db.collection('article');
        connection = db;
        return article.insertOne(userInfo);
    }).then(function(doc){//如果返回与插入有关的信息包括insertId
        callback(doc);
    }).finally(function(){
        connection.close();
    })
}

function getArticleList(page,callback){
    var p = conn.getConnection();
    var connection = undefined;
    p.then(function(db){
        var blog = db.collection('blog');
        connection = db;
        return [blog.find({type:1}).skip((page-1)*5).limit(5).toArray(),blog.find({type:1}).count()];
    },function(err){
        console.log(err);
    }).spread(function(docs,count){
        docs.forEach(function(doc){
            doc._id = doc._id.toHexString();
            doc.body = doc.body.slice(0,100);
        });
        callback({
            total:count,
            articles:docs
        })
    }).finally(function(){
        connection.close();
    })
}
//getArticleList(1,console.log);
//56629ee04d1f4060123ca49f
//getArticle('56629ee04d1f4060123ca49f',console.log);
exports.getArticleList = getArticleList;
exports.getArticle = getArticle;